package com.bainuo.doctor.common.image_support.imghandle.uploader;

import android.text.TextUtils;

import com.bainuo.doctor.common.network_engine.CallBack;
import com.bainuo.doctor.common.network_engine.UpFileServerApi;
import com.bainuo.doctor.common.network_engine.UpLoadFileCallBack;
import com.bainuo.doctor.common.network_engine.UpLoadFileResponse;
import com.bainuo.doctor.common.util.MyUtil;
import com.blankj.utilcode.utils.LogUtils;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * Created by bainuo on 2017/2/10.
 */

public class FileUploader implements IFileUpload {

    /**
     * 文件同时上传任务数
     */
    private final int MAX_TASK = 1;

    /**
     * 文件上传监听
     */
    private IFileUpload.Listener uploadListener;

    /**
     * 上传任务
     */
    private Map<String, UploadTask> uploadTask = new HashMap();

    /**
     * 上传队列
     */
    private Set<String> mUploadingQueue = new HashSet<>();

    /**
     * 上传请求
     */
    private UpFileServerApi mUpFileApi;

//    private String uploadType;
    private Map<String,String> mMapParam;
    private MyUtil.LoopHandler handler;


//    public FileUploader() {
////        mUpFileApi = new UpFileServerApiImpl();
//    }

    public FileUploader(UpFileServerApi api) {
        mUpFileApi = api;
    }


//    static FileUploader instance;
//    public static FileUploader getInstance(Context context){
//        if (instance == null)
//            instance=new FileUploader();
//        return instance;
//    }

    /**
     * 设置监听
     *
     * @param listener
     */
    @Override
    public void setUploadListener(Listener listener) {
        uploadListener = listener;
    }

    @Override
    public void setUploadApi(UpFileServerApi uploadApi) {
        mUpFileApi = uploadApi;
    }

    /**
     * 上传文件
     *
     * @param
     * @return
     */
    public synchronized boolean uploadFile(UploadTask task) {

        if (TextUtils.isEmpty(task.getUploadPath())){
            onUploadFailed(task);
            return false;
        }

        if (task.getState() == UploadTask.STATE_CANCEL){
            uploadNext();
            return false;
        }


        //如果是新任务 则加入队列
        if (!uploadTask.containsKey(task.getUploadPath())) {
            uploadTask.put(task.id, task);
        }

        //判断当前执行的任务个数 如果有空闲 则下载
        if (mUploadingQueue.size() < MAX_TASK) {
            startUpload(task);
        }else{
            task.setState(UploadTask.STATE_PRE);
        }

        return true;
    }

    /**
     * 取消请求
     *
     * @param id
     * @return
     */
    @Override
    public boolean cancelRequest(String id) {

        UploadTask task = uploadTask.remove(id);
        if (task != null)
            task.setState(UploadTask.STATE_CANCEL);

        //正在上传
//        if (mUploadingQueue.contains(id)) {
//
//        }
        return false;
    }


    /**
     * 取消所有请求
     *
     * @return
     */
    @Override
    public boolean cancelAllRequest() {

//        if (handler != null)
//            handler.stop();

        for(UploadTask task : uploadTask.values()){
            task.setState(UploadTask.STATE_CANCEL);
        }
        uploadTask.clear();
        return false;
    }


    /**
     * 测试数据
     */
    int index;
    String[] imgUrl = new String[]{
            "http://img17.3lian.com/d/file/201702/17/fe26ae1ad94f9dd0861de12248cc332d.jpg",
            "http://img2.100bt.com/upload/ttq/20131103/1383470553132_middle.jpg",
            "http://up.qqjia.com/z/04/tu6180_9.jpg",
            "http://www.qqjia.com/z/09/tu10292_19.jpg",
            "http://tupian.enterdesk.com/2014/xll/11/15/1/touxiang15.jpg",
    };


//    @Override
//    public void setUploadType(String type) {
//        uploadType = type;
//    }

    private boolean getUploadParaming;
    void getUploadParam(final String uploadType,final UploadTask task){

        if (getUploadParaming)
            return;

        getUploadParaming = true;

        if (mMapParam == null) {
            mUpFileApi.getUploadParma(uploadType, new CallBack<Map<String, String>>() {
                @Override
                public void onSuccess(Map<String, String> stringStringMap, String response, String msg) {
                    mMapParam = stringStringMap;
                    getUploadParaming = false;
                    uploadNext();
                }

                @Override
                public void onFailed(String status, String response, String msg) {
                    getUploadParaming = false;
                    onUploadFailed(task);
                }
            });
        }
    }


    public void onUploadFailed(UploadTask task){
        task.setState(UploadTask.STATE_FAILED);
        uploadTask.remove(task.id);
        mUploadingQueue.remove(task.id);
        uploadNext();

        if (uploadListener != null) {
            uploadListener.onUploadFailed(task);
        }
    }

    /**
     * 开始上传文件
     *
     * @param task
     */
    private synchronized void startUpload(final UploadTask task) {

        final String id = task.id;

        //判断任务是否已经完成
        if (task.getState() == UploadTask.STATE_COM) {
            //移除任务 进行下一个下载
            uploadTask.remove(id);
            uploadNext();
            return;
        }

        if (mMapParam == null){
            getUploadParam(task.getUploadType(),task);
            return;
        }

        //添加入下载队列
        mUploadingQueue.add(id);
        task.setState(UploadTask.STATE_ING);



        Map param = new HashMap();
        String url = null;
        for(String key : mMapParam.keySet()){
            if(key.equals("url")){
                url = mMapParam.get(key);
            }else{
                param.put(key,mMapParam.get(key));
            }

        }
        if(url == null) {
            onUploadFailed(task);
            uploadNext();
            return;
        }

        param.put("key", UUID.randomUUID());

        mUpFileApi.upLoadFile(url,param,new File(task.getUploadPath()), new UpLoadFileCallBack<UpLoadFileResponse>() {
            @Override
            public void onProgressUpdate(int percentage, long uploaded, long total) {
                LogUtils.e("tag", "percentage:" + percentage + ";uploaded:" + uploaded + ";total:" + total);

                task.setProgress(percentage);
                if (uploadListener != null)
                    uploadListener.onUploadProgress(task);


            }

            @Override
            public void onError() {
                LogUtils.e("tag", "onfileupload onError");
                onFailed(null,null,null);
            }

            @Override
            public void onFinish() {
                LogUtils.e("tag", "onfileupload onFinish");

                onProgressUpdate(100,0,0);
            }

            @Override
            public void onSuccess(UpLoadFileResponse upLoadFileResponse, String response, String msg) {
                LogUtils.e("tag", "onfileupload sucess:" + upLoadFileResponse + "");

                uploadTask.remove(id);
                mUploadingQueue.remove(id);

                task.setUrl(upLoadFileResponse.getFullpath());
                task.setState(UploadTask.STATE_COM);
                if (uploadListener != null) {
//                    uploadListener.onUploadProgress(task);
                    uploadListener.onUploadSuccess(task);
                }




                uploadNext();



//                uploadTask.remove(id);
//                mUploadingQueue.remove(id);
//
//                if (uploadListener != null)
//                    uploadListener.onUploadSuccess(id,"http://img2.100bt.com/upload/ttq/20131103/1383470553132_middle.jpg");
//                uploadNext();

//                MyUtil.runLoop(7000, new MyUtil.Loop() {
//                    @Override
//                    public boolean doexec() {
//
//                        uploadTask.remove(path);
//                        mUploadingQueue.remove(path);
//                        if (uploadListener != null)
//                            uploadListener.onUploadSuccess(path);
//
//                        uploadNext();
//                        return false;
//                    }
//                });

            }

            @Override
            public void onFailed(String status, String response, String msg) {
                LogUtils.e("tag", "onfailed upload Failed:" + msg + "");

                onUploadFailed(task);
            }
        });

    }

    /**
     * 上传下一个任务
     */
    private synchronized void uploadNext() {

        for (UploadTask task : uploadTask.values()) {
            if (task.getState() == UploadTask.STATE_PRE ) {
                startUpload(task);
                break;
            }
        }
    }
}
